﻿/*
	Copyright 2008 CATsoft Development GmbH

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
/*
	XML Parser
*/

/***********************************************************************
 Simple XML Parser
***********************************************************************/
function SimpleXmlParser(xmlDoc) {
  this.xmlDoc = xmlDoc;  
  this.parseError = xmlDoc.parseError;
  if (this.parseError.errorCode != 0) {
		showError( "Error", "SimpleXmlParser ERROR: " + this.parseError.reason);
	}

/***********************************************************************
 Check Error
***********************************************************************/
SimpleXmlParser.prototype.checkError = function(checkonly)
{
  var xmlDoc = this.xmlDoc;
  var items = [];
	var value='';

  if (this.parseError.errorCode != 0) {
    showError("Error", "SimpleXmlParser ERROR: " + this.parseError.reason);
  } 
	else 
	{
		var objNodeList = xmlDoc.getElementsByTagName("err");
	  if (objNodeList.length == 1)
		{
			var xmlItem = objNodeList.item(0);
			value = xmlItem.getAttribute('msg');
			
		}
	}

	if (value.length > 0 ) 
		if(checkonly)
		    debug.warning("Info: " + value)
		else
		    debug.warning("Error: " + value);

  return value;
}

/***********************************************************************
 Get Child value
***********************************************************************/
SimpleXmlParser.prototype.getValue = function(key)
{
  var xmlDoc = this.xmlDoc;
  
  if (this.parseError.errorCode != 0) {
      showError( "Error", "SimpleXmlParser ERROR: " + this.parseError.reason);
  } else {
	var objNodeList = xmlDoc.getElementsByTagName(key);
	  if (objNodeList.length >= 1)
		{
			
	  var xmlItem = objNodeList.item(0);
			var child = xmlItem.childNodes.item(0);			
			value = child.nodeValue;
		}
	}
  return value;
}

/***********************************************************************
	Get Attribute
***********************************************************************/
SimpleXmlParser.prototype.getAttributeValue = function(key, attribute)
{
  var xmlDoc = this.xmlDoc;
  
  if (this.parseError.errorCode != 0) {
      showError("Error", "SimpleXmlParser ERROR: " + this.parseError.reason);
  } else {
	var objNodeList = xmlDoc.getElementsByTagName(key);
	  if (objNodeList.length >= 1)
		{
			
	  var xmlItem = objNodeList.item(0);
			value = xmlItem.getAttribute( attribute );
		}
	}
  return value;
}

/***********************************************************************
	Parser retrieved lists
***********************************************************************/
SimpleXmlParser.prototype.parseLists = function(  ){
  var xmlDoc = this.xmlDoc;
  var emptyArray = new Array();
	
	lists = emptyArray
	if (this.parseError.errorCode != 0) {
	    showError( "Error", "SimpleXmlParser ERROR: " + this.parseError.reason);
  } 
	else 
	{
		var objNodeList = xmlDoc.getElementsByTagName("list");
		for (var i = 0; i < objNodeList.length; ++i) {
			var xmlItem = objNodeList.item(i);
			var listItem 
			listItem = new Object();

			listItem.id = xmlItem.getAttribute( "id" );
			listItem.name = xmlItem.getAttribute( "name" );
			listItem.position = xmlItem.getAttribute( "position" );

			// Check for Smartlist
			var filter = xmlItem.getElementsByTagName("filter");
			if(filter.length>0)
			{
				try
				{
					listItem.filter = filter[0].firstChild.nodeValue;
				}
				catch(e)
				{
					listItem.filter = "(NOT name:@#@@####80##@@#90)";
				}
			}
			else
				listItem.filter = "";
			
			listColor = getListColor( listItem.id);
			if (getListShow(listItem.id, listItem.position) == "true")
			    listShow = 1
			else
			    listShow = 0;
			    
			listItem.color = listColor;
			listItem.show = listShow;
			lists.push( listItem );
		}
  }  
  return lists.length
}

/***********************************************************************
 Simple retrieved locations
***********************************************************************/
SimpleXmlParser.prototype.parseLocations = function( ){
  var xmlDoc = this.xmlDoc;
	var emptyArray = new Array();

	locations = emptyArray;
	if (this.parseError.errorCode != 0) {
	    showError("Error", "SimpleXmlParser ERROR: " + this.parseError.reason);
  } 
	else {
		var objNodeList = xmlDoc.getElementsByTagName("location");
		for (var i = 0; i < objNodeList.length; ++i) {
			var xmlItem = objNodeList.item(i);
			var locationItem 
			locationItem = new Object();
			
			locationItem.id = xmlItem.getAttribute( "id" );
			locationItem.name = xmlItem.getAttribute( "name" );
			locations.push( locationItem );
		}
  }  
  return locations.length
}

/***********************************************************************
 Display all available methods
***********************************************************************/
SimpleXmlParser.prototype.parseMethods = function( ){
  var xmlDoc = this.xmlDoc;
	var emptyArray = new Array();

	if (this.parseError.errorCode != 0) {
	    showError("Error", "SimpleXmlParser ERROR: " + this.parseError.reason);
  } 
	else {
		var objNodeList = xmlDoc.getElementsByTagName("method");
		for (var i = 0; i < objNodeList.length; ++i) {
			var xmlItem = objNodeList.item(i);
			debug.info( objNodeList[i].childNodes.item(0).nodeValue)
		}
  }  
  return 0;
}

/***********************************************************************
 Simple parse task
***********************************************************************/
SimpleXmlParser.prototype.parseTasks = function(listid, listColor, smartList) {
    var xmlDoc = this.xmlDoc;
    var now = new Date();

    today = new Date(now.getFullYear(), now.getMonth(), now.getDate());

    if (this.parseError.errorCode != 0) {
        showError("Error", "SimpleXmlParser ERROR: " + this.parseError.reason);
    } else {

        var objTaskList = xmlDoc.getElementsByTagName("list");
        for (var k = 0; k < objTaskList.length; k++) {

            listid = objTaskList.item(k).getAttribute("id");

            var objNodeList = objTaskList.item(k).getElementsByTagName("taskseries");
            for (var i = 0; i < objNodeList.length; ++i) {
                var xmlItem = objNodeList.item(i);
                var taskItem
                taskItem = new Object()
                taskItem.name = xmlEscape(xmlItem.getAttribute("name"));
                taskItem.seriesid = xmlItem.getAttribute("id");
                taskItem.color = listColor;
                taskItem.listid = listid
                taskItem.location = xmlItem.getAttribute("location_id");
                taskItem.url = xmlItem.getAttribute("url");
                taskItem.smartList = smartList;

                // GetDetails
                var taskDetails = xmlItem.getElementsByTagName("task")
                if (taskDetails[0].getAttribute("deleted").length == 0) {
                    if (taskDetails[0].getAttribute("completed").length != 0)
                        taskItem.name = "*" + taskItem.name;
                    taskItem.completed = taskDetails[0].getAttribute("completed");
                    taskItem.id = taskDetails[0].getAttribute("id");
                    taskItem.due = createDate(taskDetails[0].getAttribute("due"));
                    taskItem.estimate = taskDetails[0].getAttribute("estimate");
                    if (taskItem.due == "") {
                        taskItem.dueIn = -9999
                    }
                    else {
                        taskDue = new Date(taskItem.due.getFullYear(), taskItem.due.getMonth(), taskItem.due.getDate());
                        taskItem.dueIn = Math.ceil((taskDue.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
                    }
                    taskItem.has_due_time = taskDetails[0].getAttribute("has_due_time");
                    taskItem.priority = taskDetails[0].getAttribute("priority");
                    taskItem.timeoutToken = -1;
                    taskItem.note = "";
                    var taskNotes = xmlItem.getElementsByTagName("notes");
                    if (taskNotes.length > 0) {
                        var note = taskNotes[0].getElementsByTagName("note");
                        for (var j = 0; j < note.length; j++) {
							taskItem.note += note[j].getAttribute("title") + "\n";
							if (note[j].firstChild != null) 
								taskItem.note += note[j].childNodes.item(0).nodeValue + "\n";
                            
						}
                        taskItem.note = xmlEscape(taskItem.note);
                    }

                    // Get Tags
                    taskItem.tags = "";
                    var tags = xmlItem.getElementsByTagName("tags");
                    if (tags.length > 0) {
                        var tag = tags[0].getElementsByTagName("tag");
                        var tagArray = new Array();
                        for (var j = 0; j < tag.length; j++) {
                            tagArray.push(tag[j].childNodes.item(0).nodeValue);
                            addToArray(tagList, tag[j].childNodes.item(0).nodeValue, true);
                        }
                        tagArray.sort()
                        for (var j = 0; j < tagArray.length; j++)
                            taskItem.tags += tagArray[j] + ",";
                        taskItem.tags = taskItem.tags.substr(0, taskItem.tags.length - 1)
                    }

                    // Get Repeats
                    var repeats = xmlItem.getElementsByTagName("rrule")
                    if (repeats.length > 0)
                        taskItem.repeat = RTM.convertFrequency("EVERY=" + repeats[0].getAttribute("every") + ";" + repeats[0].childNodes.item(0).nodeValue);
                    else
                        taskItem.repeat = '';

                    tasks.push(taskItem);
                }
            }
        }
    }
    return tasks.length;
}

/***********************************************************************
 Simple adding task
***********************************************************************/
SimpleXmlParser.prototype.parseAddTasks = function( listid ){
  var xmlDoc = this.xmlDoc;
	var taskItem 
	
  if (this.parseError.errorCode != 0) {
      showError( "Error", "SimpleXmlParser ERROR: " + this.parseError.reason);
  } else {

		var objNodeList = xmlDoc.getElementsByTagName("taskseries");
		for (var i = 0; i < objNodeList.length; ++i) {
			var xmlItem = objNodeList.item(i);
				taskItem = new Object()
				taskItem.name = xmlEscape( xmlItem.getAttribute( "name" ) );
				taskItem.seriesid = xmlItem.getAttribute("id");
				taskItem.listid = listid

				// GetDetails
				var taskDetails = xmlItem.getElementsByTagName("task")
				if (taskDetails[0].getAttribute("completed").length + taskDetails[0].getAttribute("deleted").length == 0) {
					taskItem.id = taskDetails[0].getAttribute( "id" );
				}
				
		}  
		return taskItem;
	}
}

}